# -*- coding: utf-8 -*-
from datetime import datetime
import threading
from Model.ModelRequest import request_model
from Util.Return import get_current_time
from Util.Process import INFO
from Util.SQL import insert, update, select


class Task:
    def __init__(self, model_id, data_list):
        ############################初始化任务信息
        self.model_id = model_id  # 任务所属的模型
        self.scene_id = data_list[0]  # 数据景号
        self.data_list = data_list  # 当前数据集的ID
        self.attribute = "0_99_0_99"  # 附属信息 当前:数据瓦片范围号
        self.user_id = 0  # 用户ID
        self.state = "init"  # 0为就绪、1为等待、2为运行、3为成功、4为失败
        self.task_id = f"{self.model_id}+{self.attribute}+{self.scene_id}"  # 任务ID
        self.json = {"data_list": self.data_list}  # 额外信息

    def init(self):
        self.status("init")
        task_num = select(f"select count(1) as num from task where task_id = '{self.task_id}' and state='success' ")[0]['num']
        if task_num > 0:
            update_json = {'date': get_current_time()}
            update(update_json, f'task_id = "{self.task_id}"', 'task')
            self.end("success")
        else:
            json_task = {
                'task_id': self.task_id,
                'model_id': self.model_id,
                'scene_id': self.scene_id,
                'attribute': self.attribute,
                'date': get_current_time(),
                'state': self.state,
                'user_id': self.user_id,
                'json': self.json
            }
            insert([json_task], 'task')
            self.wait()

    def wait(self):
        self.status("wait")
        self.run()  # 进入运行状态

    def run(self):
        self.status("run")
        try:
            request_model(self.model_id, self.data_list, [self.task_id, self.attribute])
            self.end("success")
        except Exception as e:
            INFO("ERROR", f"TASK RUN ERROR: {e}")
            self.end("error")

    def end(self, state):
        self.status(state)

    def status(self, state):
        self.state = state
        INFO("INFO", f"TASK {self.task_id} {self.state}")
        update_json = {'state': self.state}
        update(update_json, f'task_id = "{self.task_id}"', 'task')


def init_task(model_id, data_list):  # 创建一个新的任务
    task = Task(model_id, data_list)
    thread = threading.Thread(target=task.init)
    thread.start()
    thread.join()  # 待执行结束再返回
    return task.task_id
